package com.itjin.health.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itjin.health.common.BaseResponse;
import com.itjin.health.common.ResultUtils;
import com.itjin.health.domain.dto.AppointmentCancelRequest;
import com.itjin.health.domain.dto.OfflineAssessmentRequest;
import com.itjin.health.domain.dto.OnlineAssessmentDetailRequest;
import com.itjin.health.domain.dto.OnlineAssessmentRequest;
import com.itjin.health.domain.entity.OfflineAssessmentAppointment;
import com.itjin.health.domain.entity.OnlineAssessmentAppointment;
import com.itjin.health.domain.vo.OfflineAppointmentDetailVO;
import com.itjin.health.domain.vo.OnlineAppointmentDetailVO;
import com.itjin.health.exception.BusinessException;
import com.itjin.health.exception.ErrorCode;
import com.itjin.health.service.AssessmentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/assessment")
@Api(tags = "评估接口")
@Slf4j
public class AssessmentController {

  @Resource
  private AssessmentService assessmentService;

  /**
   * 申请线下评估
   *
   * @param request 线下评估请求
   * @return 预约ID
   */
  @PostMapping("/offline/apply")
  @ApiOperation(value = "申请线下评估")
  public BaseResponse<Integer> applyOfflineAssessment(@RequestBody OfflineAssessmentRequest request) {
    if (request == null) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR);
    }

    Integer appointmentId = assessmentService.applyOfflineAssessment(request);
    return ResultUtils.success(appointmentId);
  }

  /**
   * 取消线下评估预约
   *
   * @param request 取消预约请求
   * @return 取消结果
   */
  @PostMapping("/offline/cancel")
  @ApiOperation(value = "取消线下评估预约")
  public BaseResponse<Boolean> cancelOfflineAppointment(@RequestBody AppointmentCancelRequest request) {
    if (request == null) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR);
    }

    boolean result = assessmentService.cancelOfflineAppointment(request);
    return ResultUtils.success(result);
  }

  /**
   * 获取学生的预约列表
   *
   * @param studentId 学生ID
   * @param status    状态（可选，默认全部）
   * @param current   当前页（默认1）
   * @param size      每页大小（默认10）
   * @return 预约分页列表
   */
  @GetMapping("/offline/list")
  @ApiOperation(value = "获取线下学生的预约列表")
  public BaseResponse<Page<OfflineAssessmentAppointment>> listStudentAppointments(
      @RequestParam Integer studentId,
      @RequestParam(required = false, defaultValue = "all") @ApiParam("预约状态") String status,
      @RequestParam(defaultValue = "1") @ApiParam("当前页") long current,
      @RequestParam(defaultValue = "10") @ApiParam("每页大小") long size) {

    Page<OfflineAssessmentAppointment> page = assessmentService.listStudentAppointments(studentId, status, current,
        size);
    return ResultUtils.success(page);
  }

  /**
   * 获取预约详情
   *
   * @param appointmentId 预约ID
   * @return 预约详情
   */
  @GetMapping("/offline/{appointmentId}")
  @ApiOperation(value = "获取线下预约详情")
  public BaseResponse<OfflineAssessmentAppointment> getAppointmentById(@PathVariable Integer appointmentId) {
    if (appointmentId == null) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR);
    }

    OfflineAssessmentAppointment appointment = assessmentService.getAppointmentById(appointmentId);
    return ResultUtils.success(appointment);
  }

  /**
   * 申请线上评估（详细版）
   *
   * @param request 线上评估详细请求
   * @return 预约ID
   */
  @PostMapping("/online/apply")
  @ApiOperation(value = "申请线上评估（详细版）")
  public BaseResponse<Integer> applyOnlineAssessmentDetail(@RequestBody OnlineAssessmentDetailRequest request) {
    if (request == null) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR);
    }

    Integer appointmentId = assessmentService.applyOnlineAssessmentDetail(request);
    return ResultUtils.success(appointmentId);
  }

  /**
   * 取消线上评估预约
   *
   * @param request 取消预约请求
   * @return 取消结果
   */
  @PostMapping("/online/cancel")
  @ApiOperation(value = "取消线上评估预约")
  public BaseResponse<Boolean> cancelOnlineAppointment(@RequestBody AppointmentCancelRequest request) {
    if (request == null) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR);
    }

    boolean result = assessmentService.cancelOnlineAppointment(request);
    return ResultUtils.success(result);
  }

  /**
   * 获取学生的线上预约列表
   *
   * @param studentId 学生ID
   * @param status    状态（可选，默认全部）
   * @param current   当前页（默认1）
   * @param size      每页大小（默认10）
   * @return 预约分页列表
   */
  @GetMapping("/online/list")
  @ApiOperation(value = "获取线上预约列表")
  public BaseResponse<Page<OnlineAssessmentAppointment>> listStudentOnlineAppointments(
      @RequestParam Integer studentId,
      @RequestParam(required = false, defaultValue = "all") @ApiParam("预约状态") String status,
      @RequestParam(defaultValue = "1") @ApiParam("当前页") long current,
      @RequestParam(defaultValue = "10") @ApiParam("每页大小") long size) {

    Page<OnlineAssessmentAppointment> page = assessmentService.listStudentOnlineAppointments(studentId, status, current,
        size);
    return ResultUtils.success(page);
  }

  /**
   * 获取线上预约详情
   *
   * @param appointmentId 预约ID
   * @return 预约详情
   */
  @GetMapping("/online/{appointmentId}")
  @ApiOperation(value = "获取线上预约详情")
  public BaseResponse<OnlineAssessmentAppointment> getOnlineAppointmentById(@PathVariable Integer appointmentId) {
    if (appointmentId == null) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR);
    }

    OnlineAssessmentAppointment appointment = assessmentService.getOnlineAppointmentById(appointmentId);
    return ResultUtils.success(appointment);
  }

  /**
   * 获取所有待审核的线下评估预约
   *
   * @param status  状态（可选，默认"待审核"）
   * @param current 当前页（默认1）
   * @param size    每页大小（默认10）
   * @param request HTTP请求
   * @return 预约分页列表
   */
  @GetMapping("/admin/offline/pending")
  @ApiOperation(value = "管理员/教师获取待审核的线下评估预约")
  public BaseResponse<Page<OfflineAppointmentDetailVO>> getPendingOfflineAppointments(
      @RequestParam(required = false, defaultValue = "待审核") @ApiParam("预约状态") String status,
      @RequestParam(defaultValue = "1") @ApiParam("当前页") long current,
      @RequestParam(defaultValue = "10") @ApiParam("每页大小") long size,
      HttpServletRequest request) {
    // 校验管理员/教师权限
    Integer teacherId = (Integer) request.getSession().getAttribute("userId");
    if (teacherId == null) {
      throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
    }
    // TODO: 验证是否为管理员或教师

    Page<OfflineAppointmentDetailVO> page = assessmentService.getTeacherOfflineAppointments(teacherId, status,
        current, size);
    return ResultUtils.success(page);
  }

  /**
   * 管理员/教师审核线下评估预约
   *
   * @param appointmentId 预约ID
   * @param approved      是否通过
   * @param rejectReason  拒绝原因（拒绝时必填）
   * @param teacherNote   教师备注（可选）
   * @param request       HTTP请求
   * @return 审核结果
   */
  @PostMapping("/admin/offline/review")
  @ApiOperation(value = "管理员/教师审核线下评估预约")
  public BaseResponse<Boolean> reviewOfflineAppointment(
      @RequestParam @ApiParam("预约ID") Integer appointmentId,
      @RequestParam @ApiParam("是否通过") Boolean approved,
      @RequestParam(required = false) @ApiParam("拒绝原因") String rejectReason,
      @RequestParam(required = false) @ApiParam("教师备注") String teacherNote,
      HttpServletRequest request) {
    // 校验管理员/教师权限
    Integer teacherId = (Integer) request.getSession().getAttribute("userId");
    if (teacherId == null) {
      throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
    }
    // TODO: 验证是否为管理员或教师

    // 验证参数
    if (!approved && (rejectReason == null || rejectReason.isEmpty())) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR, "拒绝预约时必须提供拒绝原因");
    }

    boolean result = assessmentService.reviewOfflineAppointment(appointmentId, teacherId, approved, rejectReason,
        teacherNote);
    return ResultUtils.success(result);
  }

  /**
   * 管理员/教师完成线下评估并提交反馈
   *
   * @param appointmentId 预约ID
   * @param feedback      教师反馈
   * @param request       HTTP请求
   * @return 完成结果
   */
  @PostMapping("/admin/offline/complete")
  @ApiOperation(value = "管理员/教师完成线下评估并提交反馈")
  public BaseResponse<Boolean> completeOfflineAppointment(
      @RequestParam @ApiParam("预约ID") Integer appointmentId,
      @RequestParam @ApiParam("教师反馈") String feedback,
      HttpServletRequest request) {
    // 校验管理员/教师权限
    Integer teacherId = (Integer) request.getSession().getAttribute("userId");
    if (teacherId == null) {
      throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
    }
    // TODO: 验证是否为管理员或教师

    boolean result = assessmentService.completeOfflineAppointment(appointmentId, teacherId, feedback);
    return ResultUtils.success(result);
  }

  /**
   * 获取所有待审核的线上评估预约
   *
   * @param status  状态（可选，默认"待审核"）
   * @param current 当前页（默认1）
   * @param size    每页大小（默认10）
   * @param request HTTP请求
   * @return 预约分页列表
   */
  @GetMapping("/admin/online/pending")
  @ApiOperation(value = "管理员/教师获取待审核的线上评估预约")
  public BaseResponse<Page<OnlineAppointmentDetailVO>> getPendingOnlineAppointments(
      @RequestParam(required = false, defaultValue = "待审核") @ApiParam("预约状态") String status,
      @RequestParam(defaultValue = "1") @ApiParam("当前页") long current,
      @RequestParam(defaultValue = "10") @ApiParam("每页大小") long size,
      HttpServletRequest request) {
    // 校验管理员/教师权限
    Integer teacherId = (Integer) request.getSession().getAttribute("userId");
    if (teacherId == null) {
      throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
    }
    // TODO: 验证是否为管理员或教师

    Page<OnlineAppointmentDetailVO> page = assessmentService.getTeacherOnlineAppointments(teacherId, status, current,
        size);
    return ResultUtils.success(page);
  }

  /**
   * 管理员/教师审核线上评估预约
   *
   * @param appointmentId   预约ID
   * @param approved        是否通过
   * @param meetingUrl      会议链接（通过时必填）
   * @param meetingId       会议ID（通过时必填）
   * @param meetingPassword 会议密码（通过时必填）
   * @param rejectReason    拒绝原因（拒绝时必填）
   * @param request         HTTP请求
   * @return 审核结果
   */
  @PostMapping("/admin/online/review")
  @ApiOperation(value = "管理员/教师审核线上评估预约")
  public BaseResponse<Boolean> reviewOnlineAppointment(
      @RequestParam @ApiParam("预约ID") Integer appointmentId,
      @RequestParam @ApiParam("是否通过") Boolean approved,
      @RequestParam(required = false) @ApiParam("会议链接") String meetingUrl,
      @RequestParam(required = false) @ApiParam("会议ID") String meetingId,
      @RequestParam(required = false) @ApiParam("会议密码") String meetingPassword,
      @RequestParam(required = false) @ApiParam("拒绝原因") String rejectReason,
      HttpServletRequest request) {
    // 校验管理员/教师权限
    Integer teacherId = (Integer) request.getSession().getAttribute("userId");
    if (teacherId == null) {
      throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
    }
    // TODO: 验证是否为管理员或教师

    // 验证参数
    if (approved) {
      if (meetingUrl == null || meetingId == null || meetingPassword == null) {
        throw new BusinessException(ErrorCode.PARAMS_ERROR, "通过预约时必须提供会议信息");
      }
    } else if (rejectReason == null || rejectReason.isEmpty()) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR, "拒绝预约时必须提供拒绝原因");
    }

    boolean result = assessmentService.reviewOnlineAppointment(
        appointmentId, teacherId, approved, meetingUrl, meetingId, meetingPassword, rejectReason);
    return ResultUtils.success(result);
  }

  /**
   * 管理员/教师完成线上评估并提交反馈
   *
   * @param appointmentId 预约ID
   * @param feedback      教师反馈
   * @param request       HTTP请求
   * @return 完成结果
   */
  @PostMapping("/admin/online/complete")
  @ApiOperation(value = "管理员/教师完成线上评估并提交反馈")
  public BaseResponse<Boolean> completeOnlineAppointment(
      @RequestParam @ApiParam("预约ID") Integer appointmentId,
      @RequestParam @ApiParam("教师反馈") String feedback,
      HttpServletRequest request) {
    // 校验管理员/教师权限
    Integer teacherId = (Integer) request.getSession().getAttribute("userId");
    if (teacherId == null) {
      throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
    }
    // TODO: 验证是否为管理员或教师

    boolean result = assessmentService.completeOnlineAppointment(appointmentId, teacherId, feedback);
    return ResultUtils.success(result);
  }

  /**
   * 管理员/教师获取评估统计数据
   *
   * @param startDate 开始日期（可选）
   * @param endDate   结束日期（可选）
   * @param request   HTTP请求
   * @return 统计数据
   */
  @GetMapping("/admin/stats")
  @ApiOperation(value = "管理员/教师获取评估统计数据")
  public BaseResponse<Object> getAssessmentStats(
      @RequestParam(required = false) @ApiParam("开始日期") String startDate,
      @RequestParam(required = false) @ApiParam("结束日期") String endDate,
      HttpServletRequest request) {
    // 校验管理员/教师权限
    Integer teacherId = (Integer) request.getSession().getAttribute("userId");
    if (teacherId == null) {
      throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
    }
    // TODO: 验证是否为管理员或教师

    Object stats = assessmentService.getAssessmentStats(startDate, endDate);
    return ResultUtils.success(stats);
  }
}